package web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Yancy xiao
 * @create 2023-04-03 11:24
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.先获得请求地址
        String requestURI = req.getRequestURI();
        //2.获取最后的/的索引
        int index = requestURI.lastIndexOf("/");
        String methodName = requestURI.substring(index + 1);

        System.out.println(methodName);
        //获得当前调用 service方法对象所属的类
        Class<? extends BaseServlet> aClass = this.getClass();

        try {
//            获得要执行的方法对象
            Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//            执行相应的方法
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
